<!--
 * @Description: 
 * @Author: @yangwenshan
 * @since: 2021-05-13 11:24:08
 * @LastAuthor: @yangwenshan
 * @lastTime: 2021-08-12 16:44:28
-->
<template>
  <a-drawer
    :title="mode == 1 ? '编辑题目类型' : '新增题目类型'"
    width="35%"
    placement="right"
    :visible="visible"
    @close="onClose"
  >
    <a-spin tip="数据加载中" :spinning="loading">
      <a-form :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" @submit="handleSubmit">
        <a-form-item label="题目名称">
          <a-input
            placeholder="请输入题目名称"
            v-decorator="[
              'name',
              {
                initialValue: editInfo.name,
                rules: [{ required: true, message: '请输入题目名称' }],
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="题目分类">
          <a-select
            show-search
            v-decorator="[
              'type',
              {
                initialValue: editInfo.type,
                rules: [{ required: true, message: '请输入题目分类' }],
              },
            ]"
            placeholder="请搜索题目分类"
            style="width: 100%"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="fetching ? undefined : null"
            @search="handleSearchType"
            @change="handleChange"
          >
            <a-spin v-if="fetching" slot="notFoundContent" size="small" />
            <a-select-option v-for="item in typeList" :key="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="类型">
          <a-select
            v-decorator="[
              'cate',
              {
                initialValue: editInfo.cate,
                rules: [{ required: true, message: '请选择类型' }],
              },
            ]"
            placeholder="请选择类型"
            style="width: 100%"
            @change="handleCateChange"
          >
            <a-select-option value="单选"> 单选 </a-select-option>
            <a-select-option value="多选"> 多选 </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="选项" required>
          <a-button type="primary" @click="addOptions"> 增加选项 </a-button>
          <a-button type="danger" style="margin-left: 12px" @click="delOptions">删除选项</a-button>
          <a-input
            v-for="(item, index) in optionsList"
            :addon-before="optionsNameMap[index]"
            :key="index"
            v-model="item.value"
          />
        </a-form-item>
        <a-form-item label="正确选项">
          <a-select
            :mode="cate === '单选' ? 'default' : 'tags'"
            v-decorator="[
              'answer',
              {
                initialValue: editInfo.answer,
                rules: [{ required: true, message: '请选择正确答案选项' }],
              },
            ]"
            placeholder="请选择正确答案选项"
            style="width: 100%"
            @change="handleAnswerChange"
          >
            <a-select-option v-for="item in optionsList" :key="item.key">
              {{ item.key }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="试题详解">
          <a-textarea
            placeholder="请输入试题详解"
            :auto-size="{ minRows: 6, maxRows: 10 }"
            v-decorator="[
              'remark',
              { initialValue: editInfo.remark, rules: [{ required: true, message: '请输入试题详解' }] },
            ]"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
          <a-button type="primary" html-type="submit"> 提交 </a-button>
          <a-button type="default" :style="{ marginLeft: '8px' }" @click="onClose"> 取消 </a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-drawer>
</template>
<script>
import { addQuestion, getQuestionDetail, updateQuestion } from '@/api/question'
import { getTypeList } from '@/api/questionType'
export default {
  data() {
    return {
      visible: false,
      loading: false,
      formLayout: 'horizontal',
      form: this.$form.createForm(this),
      mode: 0, // 0新增模式,1编辑模式
      editInfo: {},
      typeList: [],
      fetching: false,
      cate: '单选', //题目是单选还是多选
      optionsList: [
        {
          key: 'A',
          value: '',
        },
        {
          key: 'B',
          value: '',
        },
        {
          key: 'C',
          value: '',
        },
        {
          key: 'D',
          value: '',
        },
      ],
      optionsNameMap: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'],
    }
  },
  methods: {
    showDrawer(record, mode) {
      this.form.resetFields()
      this.mode = mode
      if (this.mode === 1) {
        this.getEditDetail(record.id)
      }
      this.visible = true
    },
    getEditDetail(id) {
      this.loading = true
      getQuestionDetail(id)
        .then((res) => {
          this.editInfo = res
          this.optionsList = res.options
          this.form.setFieldsValue({ type: res.type.id })
          this.searchTypeRequest(res.type.name)
          this.cate = res.cate
        })
        .finally(() => {
          this.loading = false
        })
    },
    addOptions() {
      let len = this.optionsList.length
      if (len > 8) {
        this.$message.warning('选项个数不能超过8个')
        return
      }
      this.optionsList.push({
        key: this.optionsNameMap[len],
        value: '',
      })
    },
    delOptions() {
      let len = this.optionsList.length
      if (len <= 4) {
        this.$message.warning('选项个数不能小于4个')
        return
      }
      this.optionsList.pop()
    },
    init() {
      this.form.resetFields()
      this.editInfo = {}
    },
    onClose() {
      this.visible = false
      this.optionsList = [
        {
          key: 'A',
          value: '',
        },
        {
          key: 'B',
          value: '',
        },
        {
          key: 'C',
          value: '',
        },
        {
          key: 'D',
          value: '',
        },
      ]
      this.editInfo = {}
      this.cate = '单选'
    },
    //验证选项内容是否填写
    validateOptions() {
      try {
        this.optionsList.forEach((item) => {
          if (!item.value) {
            throw new Error(item.key)
          }
        })
      } catch (e) {
        this.$message.error(`请填写${e.message}选项内容`)
        return false
      }

      return true
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          if (!this.validateOptions()) {
            return
          }
          const data = { ...values }
          if (this.cate === '单选') {
            data.answer = JSON.stringify([data.answer])
          } else if (this.cate === '多选') {
            data.answer = JSON.stringify(data.answer)
          }
          data.options = JSON.stringify(this.optionsList)
          if (this.mode === 0) {
            this.add(data)
          } else if (this.mode === 1) {
            this.edit(this.editInfo.id, data)
          }
        }
      })
    },
    add(data) {
      addQuestion(data).then((res) => {
        this.$message.success('新增成功')
        this.$emit('refresh')
        this.init()
        this.onClose()
      })
    },
    edit(id, data) {
      updateQuestion(id, data).then(() => {
        this.$message.success('修改成功')
        this.$emit('refresh')
        this.init()
        this.onClose()
      })
    },
    searchTypeRequest(name) {
      this.fetching = true
      getTypeList({ name: name, page: 1, page_size: 10 })
        .then((res) => {
          this.typeList = res.data
        })
        .finally(() => {
          this.fetching = false
        })
    },
    handleSearchType(value) {
      this.searchTypeRequest(value)
    },
    handleChange(value) {
      this.searchTypeRequest(value)
    },
    //单选，多选类型切换时清空正确答案框
    handleCateChange(val) {
      this.cate = val
      this.form.setFieldsValue({ answer: [] })
    },
    //答案改变
    handleAnswerChange(selectedItems) {
      if (this.cate === '多选') {
        let result = selectedItems.sort((a, b) => {
          let x1 = a.toUpperCase()
          let x2 = b.toUpperCase()
          if (x1 < x2) {
            return -1
          }
          if (x1 > x2) {
            return 1
          }
          return 0
        })
        this.form.setFieldsValue({ answer: result })
      }
    },
  },
}
</script>
<style lang="less" scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
